package com.huike.service;

import com.huike.dao.*;
import com.huike.po.*;

import com.huike.pojo.*;
import com.huike.websocket.ChatWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;


@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private FriendDAO friendDAO;
    @Autowired
    private P2pDAO p2pDAO;
    @Autowired
    private GroupDAO groupDAO;
    @Autowired
    private SysCustomDAO sysCustomDAO;
    @Autowired
    private ChatWebSocketHandler webSocket;

    @Autowired
    private HashMap<String,Object> chatRecordList;
    @Autowired
    private  PushEventObject pushEventObject;
    @Autowired
    private  MsgUpdateObject msgUpdateObject;
    @Autowired
    private  UserOnline userOnline;
    @Autowired
    private LoginCallBack callBack;


    @Override
    public User login(LoginForm loginUser){
        String account = loginUser.getLoginAccount();
        int roleId = loginUser.getLoginRole();
        // 匹配用户
        User user =userDAO.selectUserByAccountAndRole(account,roleId);
        // 登录成功
        if (user !=null) {
            // 更新用户的在线状态
            userOnline.setAccount(loginUser.getLoginAccount());
            userOnline.setUonline_status(1);
            if (loginUser.getLoginClient().equals("win"))
                userOnline.setUclient_id(1);
            else if (loginUser.getLoginClient().equals("mobile"))
                userOnline.setUclient_id(2);
            userDAO.updateUserStatus(userOnline);
        }
        return user;
    }

    @Override
    public boolean register(RegisterForm user) {
        String account = user.getRegisterAccount();
        String password = user.getRegisterPass();
        try {
            int role = user.getRegisterRole();
            boolean res = userDAO.insertUserAccount(account, password);
            res &= userDAO.updateUserRole(account, role);
            if(res) {
                return true;
            }
            else
                return false;
        } catch (Exception e){
            return false;
        }

    }

    @Override
    public UserDetail searchUserByAccount(String account) {
        UserDetail user = userDAO.selectUserDetailByAccount(account);
        return user;
    }


    @Override
    /**
     * 用户上线后，给所有订阅该用户在线状态的账号，发送上线提醒
     */
    public void sendOnlineSubscribe(User onUser) {
        //查找订阅用户在线状态的账号列表
        List<User> subscribeList = userDAO.selectSubscribeList(onUser.getAccount());
        for (User user: subscribeList){
            System.out.println(user);
        }
        if(subscribeList.size() > 0){
            // 设置订阅事件对象内容
            pushEventObject.setEventType("EventOnlineState");
            pushEventObject.setEventContent("online");
            pushEventObject.setEventFrom(onUser.getAccount());
            // 发送上线提醒
            webSocket.sendSubscribeToUsers(pushEventObject,subscribeList);
        }

        // 查找好友列表
        List<Friend> friendList = friendDAO.selectFriendListBasic(userOnline.getAccount());
        if(friendList.size() > 0){
            // 设置订阅事件对象内容
            msgUpdateObject.setUpdateType("UpdateFriendOnlineState");
            msgUpdateObject.setUpdateContent("online");
            msgUpdateObject.setUpdateFrom(userOnline.getAccount());
            // 更新在线好友列表中的该用户在线状态
            webSocket.sendUpdateToUsers(msgUpdateObject,friendList);
        }

    }

    @Override
    /**
     * 用户下线后，给所有订阅该用户在线状态的账号，发送下线提醒
     */
    public void sendOfflineSubscribe(UserOnline userOnline) {
        //查找订阅用户在线状态的账号列表
        List<User> subscribeList = userDAO.selectSubscribeList(userOnline.getAccount());
        //修改用户在线状态
        userOnline.setUonline_status(0);
        userDAO.updateUserStatus(userOnline);
        if(subscribeList.size() > 0){
            //设置订阅事件对象内容
            pushEventObject.setEventType("EventOnlineState");
            pushEventObject.setEventContent("offline");
            pushEventObject.setEventFrom(userOnline.getAccount());
            //调用ChatWebSocketHandler类中的自定义方法，发送下线提醒
            webSocket.sendSubscribeToUsers(pushEventObject,subscribeList);
        }

        // 查找好友列表
        List<Friend> friendList = friendDAO.selectFriendListBasic(userOnline.getAccount());

        if(friendList.size() > 0){
            msgUpdateObject.setUpdateType("UpdateFriendOnlineState");
            msgUpdateObject.setUpdateContent("offline");
            msgUpdateObject.setUpdateFrom(userOnline.getAccount());
            //调用ChatWebSocketHandler类中的自定义方法，修改好友的用户在线状态
            webSocket.sendUpdateToUsers(msgUpdateObject,friendList);
        }
    }

    @Override
    /**
     * 登录成功后的信息回调
     */
    public LoginCallBack getLoginCallBack(User user) {
        //设置好友列表的回调
        List<Friend> friendListBasic = friendDAO.selectFriendListBasic(user.getAccount());
        for(Friend friend :friendListBasic) {
            friend.setGroup_name(friendDAO.selectFriendGroupNameById(friend.getGroupId()));
            int onlineNum = userDAO.selectOnlineNumByAccount(friend.getAccount());
            if( onlineNum >0)  friend.setIs_online(1);
            else  friend.setIs_online(0);
        }
        callBack.setOnFriend(friendListBasic);
        //设置好友分组的回调
        List<FriendGroup> friendGroupList = friendDAO.selectFriendGroup(user.getAccount());
        callBack.setOnFriendGroup(friendGroupList);
        //设置好友信息的回调
        List<UserDetail> friendListDetail = friendDAO.selectFriendListDetail(user.getAccount());
        callBack.setOnFriendInfo(friendListDetail);
        //设置最近P2P会话的回调
        List<p2pMessage> friendLastChatList = userDAO.selectFriendLastChat(user.getAccount());
        callBack.setOnP2PSession(friendLastChatList);
        //设置最近P2P离线未读信息数的回调
        List<p2pOfflineUnread> p2pOfflineUnreadList = userDAO.selectP2PUnReadNum(user.getAccount());
        callBack.setOnP2POfflineUnRead(p2pOfflineUnreadList);
        //设置系统通知的回调
        List<SystemCustom> systemCustomList = sysCustomDAO.selectSysCustomByAccount(user.getAccount());
        for (SystemCustom systemCustom : systemCustomList) {
            // 群邀请相关的通知
            if (!systemCustom.getGroup_id().equals("")) {
                GroupDetail groupDetail =groupDAO.findGroupById(systemCustom.getGroup_id()).get(0);
                systemCustom.setGroupDetail(groupDetail);
            }
            UserDetail fromDetail = userDAO.selectUserDetailByAccount(systemCustom.getSyscustom_from());
            systemCustom.setFromDetail(fromDetail);
        }
        callBack.setOnSysCustom(systemCustomList);
        //设置在最近离线系统通知未读数目的回调

        //设置个人信息的回调
        UserDetail myDetail =userDAO.selectUserDetailByAccount(user.getAccount());
        callBack.setOnMyInfo(myDetail);
        //设置群聊列表的回调
        List<GroupBasic> groupBasicList = groupDAO.selectGroupListBasic(user.getAccount());
        callBack.setOnGroup(groupBasicList);
        //设置群聊信息的回调
        List<GroupDetail> groupDetailList = groupDAO.selectGroupListInfo(user.getAccount());
        callBack.setOnGroupInfo(groupDetailList);
        //设置最近群聊会话的回调
        List<GroupMessage> groupLastChatList = userDAO.selectGroupLastChat(user.getAccount());
        callBack.setOnGroupSession(groupLastChatList);
        //设置最近群聊离线未读信息数的回调
        List<GroupOfflineUnread> groupOfflineUnreadList = userDAO.selectGroupUnReadNum(user.getAccount());
        callBack.setOnGroupOfflineUnRead(groupOfflineUnreadList);
        //设置每个会话聊天记录的回调
        for(Friend friend :friendListBasic) {
            List<p2pMessage> p2pMessageList = p2pDAO.selectAllP2PChatRecordByUser(user.getAccount(),friend.getAccount());
            if(p2pMessageList.size() > 0 ){
                String sessionId = "p2p-" + friend.getAccount();
                chatRecordList.put(sessionId,p2pMessageList);
            }
        }
        for (GroupBasic group : groupBasicList) {
            List<GroupMessage> groupMessageList = groupDAO.selectGroupChatRecordById(group.getGroupId());
            if(groupMessageList.size()>0){
                String sessionId = "team-" + group.getGroupId();
                chatRecordList.put(sessionId,groupMessageList);
            }
        }
        callBack.setOnMsgRecord(chatRecordList);

        return callBack;

    }

}
